import axios from "axios";
import {message} from "antd";

// 创建axios实例
const service = axios.create({
    baseURL: "http://192.168.1.161:8080",
    // timeout: 1000 * 60, // 请求超时时间
    /**
     *  动态设置请求头
     *  json: 'application/json; charset=utf-8' 默认使用
     *  form: 'application/x-www-form-urlencoded; charset=utf-8' 以这种方式传值需要用qs
     */
    headers: { //有些接口需要请求接口人的身份，这时可以在token中输入信息进行验证
        // "Content-Type": "application/x-www-form-urlencoded"
        "Content-Type": "application/json;charset=UTF-8"
    },
    // withCredentials: true, // 允许携带cookie
});

/**
 * 请求拦截
 */
service.interceptors.request.use(config => {
    // 展示loading
    return config;
}, error => {
    // Do something with request error
    alert(error);
    return Promise.reject(error);
});

/**
 * 响应拦截
 */
service.interceptors.response.use(response => {
    if (response.data && response.data.status === 1 && response.data.msg) {
        message.success(response.data.msg, 1.5)
    } else {
        message.error(response.data.msg, 1.5)
    }
    return response.data;
}, error => {
    if (error && error.response) {
        switch (error.response.status) {
            case 400:
                error.desc = '请求错误'
                break;
            case 401:
                error.desc = '未授权，请登录'
                break;
            case 403:
                error.desc = '拒绝访问'
                break;
            case 404:
                error.desc = `请求地址出错: ${error.response.config.url}`
                break;
            case 408:
                error.desc = '请求超时'
                break;
            case 500:
                error.desc = '服务器内部错误'
                break;
            case 501:
                error.desc = '服务未实现'
                break;
            case 502:
                error.desc = '网关错误'
                break;
            case 503:
                error.desc = '服务不可用'
                break;
            case 504:
                error.desc = '网关超时'
                break;
            case 505:
                error.desc = 'HTTP版本不受支持'
                break;
            default:
                error.desc = "网络错误"
        }
        message.error(error.desc)
    } else {
        alert(error);
    }
    return Promise.reject(error);
});
export default service;
